<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <link rel="stylesheet" href="/layui/css/layui.css">
    <script src="/layui/layui.js"></script>
</head>
<body>

<!--单张图片上传-->
<div class="layui-upload">
    <button type="button" class="layui-btn" id="test1">上传图片</button>
    <div class="layui-upload-list">
        <img class="layui-upload-img" id="demo1">
        <p id="demoText"></p>
    </div>
</div>
<!--多张图片上传-->
<div class="layui-upload">
    <button type="button" class="layui-btn" id="test2">多图片上传</button>
    <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
        预览图：
        <div class="layui-upload-list" id="demo2"></div>

    </blockquote>
    <button type="button" class="layui-btn" id="btn">点击上传</button>
</div>
</body>
</html>
<script type="text/javascript">
    layui.use('upload', function() {
        var $ = layui.jquery
            ,upload = layui.upload;
        //普通图片上传
        var uploadInst = upload.render({
            elem: '#test1'
            ,url: 'getImage' //改成您自己的上传接口
            ,before: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo1').attr('src', result); //图片链接（base64）
                });
            }
            ,done: function(res){
                //如果上传失败
                if(res.code > 0){
                    return layer.msg('上传失败');
                }
                //上传成功
            }
            ,error: function(){
                //演示失败状态，并实现重传
                var demoText = $('#demoText');
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function(){
                    uploadInst.upload();
                });
            }
        });


        //多张图片上传
        upload.render({
            elem: '#test2'
            ,multiple: true
            ,auto:false
            ,choose: function(obj){
                //预读本地文件示例，不支持ie8
                obj.preview(function(index, file, result){
                    $('#demo2').append('<img src="'+ result +'" alt="'+ file.name +'" class="layui-upload-img">')
                });
                files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            }
            ,done: function(res){
                //上传完毕
            },

        });
        $("#btn").click(function () {
            var form = new FormData();
            for (let i in files) {
                form.append("files", files[i]);
            }
            $.ajax({
                url: 'getImages',
                type: "post",
                dataType: "json",
                async: false,
                contentType: false,
                processData: false,
                data: form,
                success: function (result) {

                }
            })
        })

    })

</script>
